package com.neusoft.liduan.d0914;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.beans.PropertyChangeListener;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class CalSwingDemo extends JFrame {

	public CalSwingDemo() {
		setSize(450, 550);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setTitle("东软计算器");
		// 居中显示
		setLocationRelativeTo(null);
		// 设置布局管理器，使用绝对布局
		setLayout(null);
		// 添加一个文本显示框
		JLabel lbResult = new JLabel("0");
		// 设置控件的位置
		lbResult.setBounds(0, 0, 400, 100);
		// 添加到面板或窗口中
		add(lbResult);
		String[] names = { "1", "2", "3", "+", "4", "5", "6", "-", "7", "8", "9", "*", "c", "0", "=", "/" };
		int[] xs = { 0, 100, 200, 300, 0, 100, 200, 300, 0, 100, 200, 300, 0, 100, 200, 300 };
		int[] ys = { 100, 100, 100, 100, 200, 200, 200, 200, 300, 300, 300, 300, 400, 400, 400, 400 };
		StringBuilder sb = new StringBuilder();
		Cal cal = new Cal();
		for (int i = 0; i < names.length; i++) {
			System.out.println(names[i]);
			JButton btn1 = new JButton(names[i]);
			// 设置控件的位置
			btn1.setBounds(xs[i], ys[i], 100, 100);
			// 点击事件
			btn1.setActionCommand(names[i]);// 区分不同按钮
			// 接口和抽象类不能创建对象
			// 匿名内部类对象
			btn1.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					String action = e.getActionCommand();
					System.out.println("您点击了" + action + "按钮");
					/*
					 * 第一个运算数如何确定 输入运算符时，那么第一个运算数表示输入完毕 第二个运算数如何确定 输入=号的时候
					 * 
					 */
					
					if(isMark(action)) {
						cal.setX(lbResult.getText());
						cal.setMark(action);
						sb.delete(0, sb.length());
					}else if("=".equals(action)) {
						cal.setY(lbResult.getText());
						lbResult.setText(cal.result() + "");
						cal.setX(cal.result() + "");
					}else {
						sb.append(action);
						lbResult.setText(sb.toString());
					}
				}
			});
			// 添加到面板或窗口中
			add(btn1);
		}

		setVisible(true);
	}

	public static void main(String[] args) {
		new CalSwingDemo();
	}
	
	public boolean isMark(String str) {
		if(str == null || str.length() == 0) {
			return false;
		}
		
		str = str.charAt(0) + "";
		return "+-*/".contains(str);
	}

}
